from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
# from .models import User
# from mall.apps.users.models import User

# from apps.users.models import User  # 运行报错 多了apps

from users.models import User
from rest_framework.generics import ListAPIView
from rest_framework.generics import CreateAPIView
from .serialziers import RegisterCreateUserSerialzier

# Create your views here.

# APIView
# GenericAPIView
# ListAPIView ,CreateAPIView



class RegisterUserNameView(APIView):

    """
    GET     /users/usernames/(?P<username>\w{5,20})/count/


    GET     /users/usernames/?username=xxx
    POST    /users/usernames/           username=xxxx

    """

    def get(self,request,username):
        # 查询数据库 看有没有制定的数据
        count = User.objects.filter(username=username).count()
        # count = 0 不存在
        # count >= 1  存在

        context = {
            'count':count,
            'username':username     # 想返回就返回,不返回 它要数据再返回
        }

        return Response(context)

# APIView
# GenericAPIView
# ListAPIView ,CreateAPIView

# 1. 我们用到序列化器,所以排除APIView
# 2. 因为数据要入库,所以我们选项第三级视图
class RegisterCreateUserView(CreateAPIView):

    """
    POST    /users/
    1.获取前段提交的数据, username,password,password2,mobile,sms_code,allow
    2.对提交的数据进行校验
    3.保存入库
    """

    # 我的需求是将数据入库
    serializer_class = RegisterCreateUserSerialzier

    # query_set 因为我们的这个视图只是实现了数据的增加操作,没有查询数据
    # 所以 CreateAPIView 没有机会调用 get_queryset 方法

    # queryset = User.objects.all()
    # get方法是获取所有用户信息
    #def get(self,request):


from rest_framework.permissions import IsAuthenticated

# APIView
# GenericAPIView
# ListAPIView ,CreateAPIView,RetrieveAPIView
from rest_framework.generics import GenericAPIView,RetrieveAPIView
from .serialziers import UserCenterInfoSerializer

class UserCenterInfoView(GenericAPIView):


    """
    1. 访问个人中心必须是登录用户 , IsAuthenticated 只能是认证用户
    2. 得到指定用户的信息, 得到用户信息的话,用户信息是模型,模型转换为json
    """
    #必须是登录用户
    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer


    def get(self,request):
        #用户的模型如何获取
        user = request.user

        serializer = self.get_serializer(instance=user)

        return Response(serializer.data)


class UserCenterInfo2View(RetrieveAPIView):

    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    # queryset = User.objects.all()

    # 重写方法,返回 用户模型
    def get_object(self):
        return self.request.user


"""

    1. 当用户点击设置邮箱的时候,让用户输入邮箱, 输入邮箱之后,我们肯定要保存邮箱信息
    2. 我们需要发送一个激活邮件给用户
    3. 我们需要记录 邮件的激活状态

    4. 如何发送邮件(邮件的url),和如何激活邮件

"""

# APIView

# GenericAPIView
# UpdateAPIView
from rest_framework.generics import UpdateAPIView
from .serialziers import EmailUpdateSerializer

class EmailUpdateView(UpdateAPIView):

    """

    1. 把用户的信息提交过来,
    2. 更新User的email字段就可以, 肯定对email进行校验
    """

    permission_classes = [IsAuthenticated]

    serializer_class = EmailUpdateSerializer

    def get_object(self):

        return self.request.user


# APIView
# GenericAPIView
# ListAPIView,RetriveAPIView
class VerifyEmailView(APIView):


    """
    GET     /users/emails/verifications?token=xxx
    GET     /users/emails/token/
    # 1. 通过GET方式 把token给我返回回来
    # 2. 获取token,检测token
    # 3. 得到 user.id 根据userid, 修改状态就可以了
    #
    """


    def get(self,request):

        # 1. 通过GET方式 把token给我返回回来
        token = request.query_params.get('token')
        if token is None:
            return Response(status=400)
        # 2. 获取token,检测token,得到 user.id 根据userid, 返回用户模型
        user = User.user_by_token(token)
        # 3. ,修改状态就可以了
        if user is None:
            return Response(status=400)
        else:
            #修改状态就可以了
            user.email_active=True
            user.save()

        return Response({'status':'0'})

# APIView
#GenericAPIView
#CreateAPIView
from .serialziers import UserHistorySerializer,SKUSerializer
from rest_framework.mixins import CreateModelMixin
from rest_framework.generics import CreateAPIView
from django_redis import get_redis_connection
from goods.models import SKU

class UserHistoryView(GenericAPIView):
    """
    1. 我们只记录 登录用户的历史记录, 没有登录的用户是不能访问该接口的
    2. 前端发送一个请求,这个请求要有 用户信息 和 商品id
    3. 判断商品id是否正确
    4. 将记录信息保存在 Redis中

    POST     /users/browerhistories/

    """

    #添加权限
    permission_classes = [IsAuthenticated]

    serializer_class = UserHistorySerializer

    def post(self,request):

        # 1. 创建序列化器,对数据进行校验
        serializer = self.get_serializer(data=request.data,context={'request':request})
        serializer.is_valid(raise_exception=True)
        serializer.save()


        return Response({"message":'ok'})



    def get(self,request):
        """

        1. 既然是用户的历史记录,肯定是登录用户
        2. 用户的历史记录在redis中,我们从redis中获取数据
        3. 根据id查询商品信息
        4. 将模型转换为 JSON
        """
        user = request.user
        #1.连接redis
        redis_conn = get_redis_connection('history')
        #2.获取制定用户的历史记录
        ids = redis_conn.lrange('history_%s'%user.id,0,5)
        # [1,2,3,4,5]

        #3.定义一个列表来接收查询好的数据
        skus = []
        for id in ids:
            sku = SKU.objects.get(pk=id)
            skus.append(sku)

        # 4. 将模型转换为 JSON
        # skus = [SKU,SKU,SKU]
        serializer = SKUSerializer(skus,many=True)

        return Response(serializer.data)

from rest_framework import mixins
from .serialziers import AddressSerializer,AddressTitleSerializer
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.viewsets import GenericViewSet

class AddressViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    #制定序列化器
    serializer_class = AddressSerializer
    #添加用户权限
    permission_classes = [IsAuthenticated]
    #由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)


from rest_framework_jwt.views import ObtainJSONWebToken
from carts.utils import merge_cookie_to_redis

class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            #merge_cookie_to_redis(request, user, response)
            response = merge_cookie_to_redis(request, user, response)

        return response

